package com.itxiaowu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.google.gson.Gson;
import com.itxiaowu.constant.MessageConstant;
import com.itxiaowu.entity.Result;
import com.itxiaowu.pojo.Setmeal;
import com.itxiaowu.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.ArrayList;
import java.util.List;

/**
 *  套餐
 */
@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Reference
    private SetmealService setmealService;
    @Autowired
    private JedisPool jedisPool;

    /**
     *  获得全部套餐信息
     * @return
     */
    @RequestMapping("/getSetmeal.do")
    public Result getSetmeal(){

        try{
            Jedis jedis = jedisPool.getResource();
            String setmealAll = jedis.get("setmealAll");
            //转换格式
            List<Setmeal> list = null;

            //如果有数据
            if(setmealAll == null){
                list = setmealService.getSetmeal();

                String listJson = new Gson().toJson(list);
                jedis.set("setmealAll",listJson);
            }else {
                //转换数据
                list = new Gson().fromJson(setmealAll, List.class);
                System.out.println("list 的数量是" + list.size());
            }
            return new Result(true, MessageConstant.GET_SETMEAL_LIST_SUCCESS, list);
        }catch(Exception e){
            return new Result(false, MessageConstant.GET_SETMEAL_LIST_FAIL);
        }

    }

    /**
     *  查询套餐关联的数据
     */
    @RequestMapping("/findById.do")
    public Result findById(Integer id){

        try{

            // 套餐关联数据  检查组关联数据
            Jedis jedis = jedisPool.getResource();
            String setmealById = jedis.get("setmeal" + id);

            Setmeal setmeal = null;

            if(setmealById != null){
                setmeal = new Gson().fromJson(setmealById, Setmeal.class);
            }else {
                setmeal = setmealService.findById(id);

                String setmealJson = new Gson().toJson(setmeal);
                jedis.set("setmeal" + id,setmealJson);
            }
            jedis.close();
            return new Result(true, MessageConstant.GET_SETMEAL_LIST_SUCCESS, setmeal);

        }catch(Exception e){
            return new Result(false,MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

}
